package collection.list;

import java.util.Arrays;

public class MyList {
    private int length;
    private int index;
    private Object[] objects;

    public MyList(int length) {
        this.length = length;
        objects = new Object[length];
    }

    //添加方法，往集合里添加一条数据
    public void add(Object o) {
        //如果集合满溢
        if (index == length) {
            //创建新的集合。初始化长度比原来集合长度的多一半
            Object[] newobj = new Object[length + length / 2];
            //把原来集合的中的数据复制到新集合
            System.arraycopy(objects, 0, newobj, 0, length);
            //把添加的新元素添加到集合末尾
            newobj[length] = o;
            //把新集合赋值给原来的集合
            objects = newobj;
            //尾元素下表自动增长
            index++;
            //原来的集合长度增加1/2
            length = length + length / 2;
        } else {  //如果集合没有满溢
            //添加新元素到集合末尾
            objects[index] = o;
            //尾元素下表自动增长
            index++;
        }
    }

    public void show() {
        for (Object object : objects) {
            if (object != null)
                System.out.println(object);
        }
    }

    //获取集合元素个数
    public int size() {
        return index;
    }

    //判断是否包含元素
    public boolean contain(Object o) {
        for (Object object : objects) {
            if (o.equals(object))
                return true;
        }
        return false;
    }

    //根据下标，获取元素
    public Object get(int i) {
        return objects[i];
    }


    //根据下标删除元素，并返回布尔值表示是否删除成功
    public boolean remove(int i) {
        if (i >= index)
            return false;
        else {
            Object[] newobj = new Object[length];
            System.arraycopy(objects, 0, newobj, 0, i);
            System.arraycopy(objects, i + 1, newobj, i, length - i - 1);
            objects = newobj;
            index--;
            return true;
        }
    }

    @Override
    public String toString() {
        return "MyList{" +
                "length=" + length +
                ", index=" + index +
                ", objects=" + Arrays.toString(objects) +
                '}';
    }
}
